package com.kunbo.controller.local;

import com.kunbo.annotation.LoginRequired;
import com.kunbo.entity.User;
import com.kunbo.service.UserService;
import com.kunbo.util.CommunityConstant;
import com.kunbo.util.HostHolder;
import com.kunbo.util.RedisKeyUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.CookieValue;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.TimeUnit;

@Controller
public class LoginController implements CommunityConstant {

    private static final Logger logger = LoggerFactory.getLogger(LoginController.class);

    @Value("${server.servlet.context-path}")
    private String contextPath;

    @Autowired
    private UserService userService;

    @Autowired
    private HostHolder hostHolder;

    @Autowired
    private RedisTemplate redisTemplate;

    @LoginRequired
    @RequestMapping(value = "/index" ,method = RequestMethod.GET)
    public String getIndexPage(){
        //认证成功后，结果会通过SecurityContextHolder存入SecurityContext中
//        Object obj = SecurityContextHolder.getContext().getAuthentication().getPrincipal();
//        if(obj instanceof User){
//            model.addAttribute("loginUser", obj);
//        }
        return "index";
    }

    @RequestMapping(value = "/login", method = RequestMethod.GET)
    public String login(){
        return "login/login";
    }

    @RequestMapping(value = "/login", method = RequestMethod.POST)
    public String login(String username, String password, Model model, HttpServletResponse response){
        Map<String, Object> map = userService.login(username, password, DEFAULT_EXPIRED_SECONDS);
        if(map.containsKey("ticket")){
            Cookie cookie = new Cookie("ticket", map.get("ticket").toString());
            cookie.setPath(contextPath);
            cookie.setMaxAge(DEFAULT_EXPIRED_SECONDS);
            response.addCookie(cookie);
            User user = userService.findUserByTicket(map.get("ticket").toString());
            String userName = userService.findUserByTicket(map.get("ticket").toString()).getUsername();
            System.out.println(userName);
            model.addAttribute("userId", user.getId());
            model.addAttribute("username", userName);
            String userLikeKey = RedisKeyUtil.getEntityLikeKey(user.getId());
            boolean key = redisTemplate.hasKey(userLikeKey);
            if(!key){
                redisTemplate.opsForValue().set(userLikeKey, 3,30, TimeUnit.DAYS);
            }
            return "/index";
        }else {
            model.addAttribute("userameMsg", map.get("usernameMsg"));
            model.addAttribute("passwordMsg", map.get("passwordMsg"));
            return "login/login";
        }

    }

    @RequestMapping(value = "/logout", method = RequestMethod.GET)
    public String logout(@CookieValue(value = "ticket") String ticket){
        userService.logout(ticket);
//        SecurityContextHolder.clearContext();
            return "redirect:/login";
    }


    @RequestMapping(value = "/setting", method = RequestMethod.GET)
    public String Setting(Model model){
        User user = hostHolder.getUser();
        model.addAttribute("username", user.getUsername());
        model.addAttribute("userId", user.getId());
        return "/site/settings";
    }

    @RequestMapping(value = "/setting/{userId}", method = RequestMethod.GET)
    public String ToSetting(@PathVariable("userId") int userId, Model model){
        User user = userService.findUserById(userId);
        model.addAttribute("username", user.getUsername());
        model.addAttribute("userId", user.getId());
        return "/site/settings";
    }

    @RequestMapping(value = "/baidu",method = RequestMethod.GET)
    public String baidu(Model model){
        model.addAttribute("baidu", "www.baidu.com");
        return "index";
    }
}
